﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Dynamic.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using PMS.SANY.Entity;
using PMS.SANY.IBusiness;
using PMS.SANY.Util;
using PMS.SANY.Models;

namespace PMS.SANY.Business
{
    public class Sys_UserRoleBusiness : BaseRepository<Sys_UserRole>, ISys_UserRoleBusiness, IScopedDependency
    {
        private IServiceProvider SvcProvider { get; set; }
        public Sys_UserRoleBusiness(GDbContext context, IServiceProvider svcProvider)
            : base(context)
        {
            this.SvcProvider = svcProvider;
        }

        public async Task<PageResult<Sys_UserRole>> GetPageResultAsync(PageInput<Sys_UserRoleQM> query)
        {
            query.SortField = "RoleId";
            var queryable = this.GetQueryable(true).Include(i => i.Role).AsSplitQuery();
            var search = query.Search;
            if (!search.UserId.IsNullOrEmpty())
                queryable = queryable.Where(w => w.UserId == search.UserId);

            if (!search.RoleName.IsNullOrEmpty())
                queryable = queryable.Where(w => w.Role.Name.Contains(search.RoleName));

            var result = await this.GetPageResultAsync(queryable, query);
            return result;
        }

        public async Task<int> AddAsync(string userId, List<string> roleIds)
        {
            var queryable = this.GetQueryable(false);
            queryable = queryable.Where(w => w.UserId == userId && roleIds.Contains(w.RoleId));
            var list = await queryable.ToListAsync();
            var dbRoleIds = list.Select(s => s.RoleId).ToList();
            var newRoleIds = roleIds.Except(dbRoleIds).ToList();
            var listEntity = newRoleIds.Select(s => new Sys_UserRole() { UserId = userId, RoleId = s }).ToList();
            return await this.AddAsync(listEntity);
        }

        public async Task<int> DeleteAsync(string userId, List<string> roleIds)
        {
            var queryable = this.GetQueryable();
            queryable = queryable.Where(w => w.UserId == userId && roleIds.Contains(w.RoleId));
            var list = await queryable.ToListAsync();
            return await this.DeleteAsync(list);
        }
    }
}
